<template>
  <div ref="chart" :style="{ width: '68vw', height: '500px' }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'ECharts',
  props: {
    option: {
      type: Object,
      required: true
    }
  },
  mounted() {
    this.initChart();
  },
  watch: {
    option: {
      handler(newVal) {
        this.updateChart();
      },
      deep: true
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      this.updateChart()
      window.addEventListener('resize', this.onWindowResize);
    },
    updateChart() {
      this.chart.setOption(this.option);
    },
    onWindowResize() {
      this.chart.resize();
    }
  },
  beforeDestroy() {
    if (!this.chart) return;
    window.removeEventListener('resize', this.onWindowResize);
    this.chart.dispose();
    this.chart = null;
  }
};
</script>